from django.conf import settings
class MultiLangMiddleware(object):
    def process_request(self, request):
        host = request.get_host()
        if host.startswith("www."):
            host = host.replace("www.","")
        if host.endswith(settings.BASE_HOST):
            host = host.replace(".%s"%settings.BASE_HOST,"")
        if host in _get_language_code_list():
            request.session['lang_code'] = host
            request.session['django_language'] = host
        else:
            host =  _get_default_language_code()
            request.session['lang_code'] = host
            request.session['django_language'] = host
        try:
            from multilingual.languages import set_default_language
            set_default_language(host)
        except:
            pass
        try:
            from django.contrib.sites.models import Site
            site = Site.objects.get(domain__iregex=r'^.*%s\.%s' % (host, settings.BASE_HOST))
            settings.SITE_ID = site.id
        except:
            pass
        return None

def lang_code(request):
    return {'MEDIA_URL': request.session['lang_code']}
    
def _get_default_language():
    return settings.LANGUAGES[settings.DEFAULT_LANGUAGE-1]

def _get_default_language_code():
    return _get_default_language()[0]

def _get_language_code_list():
    return [lang[0] for lang in settings.LANGUAGES]